package com.bcsp.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class Test2 {
    public static void main(String[] args) throws Exception {
        String path = Test1.class.getClassLoader().getResource("").getPath();
        //解析器工厂
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //获取解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析xml文档
        Document doc = db.parse(path + "b.xml");
        NodeList nodeList = doc.getElementsByTagName("student");
//        System.out.println(nodeList.getLength());
        for (int i = 0; i < nodeList.getLength(); i++){
            Element stuElement = (Element)nodeList.item(i);
            System.out.println(stuElement.getNodeName());
            String id = stuElement.getAttribute("ID");
            System.out.println("id:"+id);

            Element nameElement = (Element)stuElement.getElementsByTagName("name").item(0);
            System.out.println("\tname:"+nameElement.getTextContent());
            Element ageElement = (Element) stuElement.getElementsByTagName("age").item(0);
            System.out.println("\tage:" + ageElement.getFirstChild().getNodeValue());
            Element genderElement = (Element) stuElement.getElementsByTagName("gender").item(0);
            System.out.println("\tgender:" + genderElement.getTextContent());

        }
    }
}
